
#include <iostream>

#include "ddc_math.h"
#include "ddc_component.h"
#include "ddc_obj.h"

// class DDC_BoxCollider2D {

DDC_Vector2 DDC_BoxCollider2D::GetCenterPosOfWorld() {
    double gox = this->_attachedGameObject->gameObjectRect.x;
    double goy = this->_attachedGameObject->gameObjectRect.y;
    double goh = this->_attachedGameObject->gameObjectRect.height;
    double gow = this->_attachedGameObject->gameObjectRect.width;

    double px = gox + gow / 2 + this->center.x;
    double py = goy + goh / 2 + this->center.y;

    return DDC_Vector2(px, py);
}

bool DDC_BoxCollider2D::Hit(DDC_BoxCollider2D &c2d) {
    DDC_Vector2 thisCenter = this->GetCenterPosOfWorld();
    DDC_Vector2 itsCenter = c2d.GetCenterPosOfWorld();

    double halfWidthA = this->size.a / 2;
    double halfWidthB = c2d.size.a / 2;

    double halfHeightA = this->size.b / 2;
    double halfHeightB = c2d.size.b / 2;

    if (DDC_Math::Intersection(
                DDC_Tuple2(thisCenter.x - halfWidthA, thisCenter.x + halfWidthA),
                DDC_Tuple2(itsCenter.x - halfWidthB, itsCenter.x + halfWidthB))
            .IsEmpty()) {
        return false;
    }

    if (DDC_Math::Intersection(
                DDC_Tuple2(thisCenter.y - halfHeightA, thisCenter.y + halfHeightA),
                DDC_Tuple2(itsCenter.y - halfHeightB, itsCenter.y + halfHeightB))
            .IsEmpty()) {
        return false;
    }

    return true;
}

// } DDC_BoxCollider2D

// class DDC_Sprite2D {

void DDC_Sprite2D::Update() {
    DDC_GameObject *go = _attachedGameObject;

    DDC_FRect spriteRect;
    double rotAngle;
    DDC_Vector2 rotAnchor;

    if (!__FixedSprite)
        go->GetAttachedScene()->WorldTransformToCamera(&go->gameObjectRect,
                                                       rotAngle,
                                                       &go->anchor,
                                                       &spriteRect,
                                                       &rotAngle,
                                                       &rotAnchor);

    DDC_SpriteRenderContext ctx;

    ctx.spriteRect = DDC_FRectToRect(&spriteRect);
    ctx.rotationCenter.x = spriteRect.width * rotAnchor.x;
    ctx.rotationCenter.y = spriteRect.height * rotAnchor.y;
    ctx.rotationAngle = rotAngle;
    ctx.flip = this->flipMode;

    ctx.keepTextureScale = keepTextureScale;

    if (this->renderer != nullptr)
        return this->renderer->Render(&ctx);
    std::cerr << "Warning: DDC_Sprite2D::renderer == nullptr (GameObject = \""
              << _attachedGameObject->name << "\")"
              << std::endl;
}

// } DDC_Sprite2D
